import * as cc from 'cc';
import { Node, UITransform, Vec3, view, Camera, director } from 'cc';
import {ENV} from "./config/main";

import { ATJSSDK } from "./AnyThinkAds/ATJSSDK";
import { ATBannerSDK } from "./AnyThinkAds/ATBannerTSSDK";
import {ATRewardedVideoSDK} from "./AnyThinkAds/ATRewardedVideoTSSDK"
import {ATNativeTSSDK,AdViewProperty} from "./AnyThinkAds/ATNativeTSSDK"
import {ATInterstitialSDK} from "./AnyThinkAds/ATIntersitialTSSDK"
import { GlobalEvent } from './events/GlobalEvent';
import { EventTypes } from './events/EventTypes';
import { UserModel } from './models/user';
// 用户API
import { UserApi } from './api/user';
import AdCustomRuleBuilder from './utils/AdCustomRuleBuilder';

// 广告类型
export enum PlacementType {
  BANNER = "BANNER", // 横幅广告
  REWARD_VIDEO = "REWARD_VIDEO", // 激励视频广告
  INTERSTITIAL = "INTERSTITIAL", // 插播广告
  NATIVE = "NATIVE", // 原生广告
  NATIVE_BANNER = "NATIVE_BANNER", // 原生横幅广告
  NATIVE_INTERSTITIAL = "NATIVE_INTERSTITIAL", // 原生插播广告
  NATIVE_REWARD_VIDEO = "NATIVE_REWARD_VIDEO", // 原生激励视频广告

  PERSONAL_CENTER_BANNER = "PERSONAL_CENTER_BANNER", // 个人中心横幅广告
  PERSONAL_CENTER_NATIVE = "PERSONAL_CENTER_NATIVE", // 个人中心原生广告
}


export class TaKuSDK {

    private static instance: TaKuSDK;
    private USER_ID = "";
    private USER_DATA = "";
    private isAdEnabled = false; // 添加广告启用状态变量
    
    // 添加广告缓存池相关属性
    private rewardedVideoCache: Map<string, boolean> = new Map(); // 激励视频缓存
    private nativeAdCache: Map<string, boolean> = new Map(); // 原生广告缓存
    private interstitialAdCache: Map<string, boolean> = new Map(); // 插播广告缓存
    private readonly CACHE_SIZE = 1; // 缓存池大小

    // 个人中心Banner广告是否已经显示
    private personalTopBannerIsLoading = false;

    private _appid = "";

    public static getInstance(): TaKuSDK {
        if (!TaKuSDK.instance) {
            TaKuSDK.instance = new TaKuSDK();
        }
        return TaKuSDK.instance;
    }

    private constructor() {
        // 检查广告是否启用
        this.isAdEnabled = ENV.AD_OPEN === true;
        console.log("广告功能状态:", this.isAdEnabled ? "开启" : "关闭");
    }

    public init(userId: string, userData: string): void {
        this.USER_ID = userId;
        this.USER_DATA = userData;
        console.log("TaKuSDK init");
        
        // 只有在广告启用时才初始化广告SDK
        if (this.isAdEnabled) {
            this.initATJSSDK();
            // 初始化Banner广告
            if(ENV.BANNER_OPEN){
                this.initBannerTSSDK();
            }

            if(ENV.NATIVE_OPEN){
                this.initNativeAd();

                // 预加载个人中心原生广告
                const userData = new AdCustomRuleBuilder()
                    .setUserId(this.USER_ID)
                    .setAdScene('personal_center')
                    .build();
                this.preloadNativeAd(PlacementType.PERSONAL_CENTER_NATIVE, userData);
            }

            // 初始化激励广告
            if(ENV.REWARD_VIDEO_OPEN){
                this.initRewardedVideoTSSDK();
            }
        } else {
            console.log("广告功能已关闭，跳过广告SDK初始化");
        }
    }
   

    // 初始化ATJSSDK
    initATJSSDK(){
        // const ad_data = {"id":"fc2af7587683bbd982083f32f1d8dc60_8853170_1748683196850","publisher_revenue":0.001,"publisher_revenue_cny":0.001,"currency":"CNY","country":"CN","adunit_id":"b682d67e021efa","adunit_format":"RewardedVideo","precision":"publisher_defined","network_type":"Network","network_placement_id":"966631072","ecpm_level":1,"segment_id":0,"scenario_reward_name":"reward_item","scenario_reward_number":1,"custom_rule":{"interest":"game"},"network_firm_id":15,"adsource_id":"8853170","adsource_index":0,"adsource_price":1,"adsource_price_cny":1,"adsource_isheaderbidding":0,"ext_info":{"expireTimestamp":1748693401000,"sdk_bidding_type":0,"style_category":40090,"pro_type":0,"tag_id":"8d89fe0ace6cb5037e098fba25d1e1c4","ad_token":"V548VbZkjJXcsCmeCCGWLoba3F2X09g0pGF3W0IQ2HGYL9EpFX3iiVTZRYFssovUEHiwOGP34n9GG+zF0atnqFNTjLQVtzem5u0GjRyqihK7lCuBVSIz2qNLuNFJqkhAhzcEOYIzl8Yr9XyU1i85yQRZOE8CduEKlbMSrf4wR0JWTIAb6jMlyHru9Chp1kva","at_reward_info":{"tt_bundle":null,"tt_reward_type":0},"request_id":"9413a592-1eb4-4a5e-a22e-38a9017db1f1u4292","adSceneType":3,"materialMetaIsFromPreload":false},"reward_custom_data":"{'interest':'game'}","abtest_id":682764,"user_load_extra_data":{"user_custom_data":"{'interest':'game'}","user_id":"interest_game0jlw6r9vlcq","userID":"interest_game0jlw6r9vlcq","media_ext":"{'interest':'game'}"},"placement_type":1,"bid_floor":0,"ad_source_type":1,"ad_source_custom_ext":"","url_tag_params":"{}","network_name":"CSJ","show_custom_ext":"","s_id":0,"req_id":"fc2af7587683bbd982083f32f1d8dc60","bid_type":0};
        // this.uploadoRewardedVideoAdRewarded("b682d67e021efa", ad_data);


        // local 本地获取光卡进度，如果进度大于0，则显示光卡广告
    

        if (!this.isAdEnabled) return;
        
        // 设置调试模式
        ATJSSDK.setLogDebug(ENV.DEBUG);

        // 初始化自定义参数
        ATJSSDK.initCustomMap(ENV.CUSTOM_MAP.APP);

        // 获取平台对应的RewardedVideo ID
        let customPlacementId = this.getPlacementId(PlacementType.REWARD_VIDEO);
        
        // 设置广告位自定义参数
        ATJSSDK.setPlacementCustomMap(customPlacementId, ENV.CUSTOM_MAP.PLACEMENT);
        
        // ATJSSDK.setGDPRLevel(ATJSSDK.PERSONALIZED); 

        // 获取GDPR级别
        let GDPRLevel = ATJSSDK.getGDPRLevel();
        ATJSSDK.printLog("当前GDPR级别：" + GDPRLevel);


        // 根据平台初始化SDK
        if (cc.sys.os === cc.sys.OS.IOS) {           
            console.log("初始化IOS SDK", ENV.SDK.IOS.APP_ID, ENV.SDK.IOS.APP_KEY);
            this._appid = ENV.SDK.IOS.APP_ID;
            ATJSSDK.initSDK(ENV.SDK.IOS.APP_ID, ENV.SDK.IOS.APP_KEY);
        } else if (cc.sys.os === cc.sys.OS.ANDROID) {
            console.log("初始化Android SDK", ENV.SDK.ANDROID.APP_ID, ENV.SDK.ANDROID.APP_KEY);
            this._appid = ENV.SDK.ANDROID.APP_ID;
            ATJSSDK.initSDK(ENV.SDK.ANDROID.APP_ID, ENV.SDK.ANDROID.APP_KEY);
        }


        // 初始化游戏用户官卡等级
        const game_level_key = "game_level" + this._appid;
        const game_level = localStorage.getItem(game_level_key);
        if(!game_level){
            
            localStorage.setItem(game_level_key, "1");
        }


        // 获取用户位置并处理GDPR
        ATJSSDK.getUserLocation(function (userLocation) {
             ATJSSDK.printLog("获取用户位置回调：" + userLocation);

            if (userLocation === ATJSSDK.kATUserLocationInEU) {
                if(ATJSSDK.getGDPRLevel() === ATJSSDK.UNKNOWN) {
                    ATJSSDK.showGDPRAuth();
                }
            }
        });
    }

    /**
     * 获取对应平台的广告位ID
     * @param type 广告类型
     * @returns 广告位ID
     */
    getPlacementId(type: PlacementType = PlacementType.BANNER) {
        if (!this.isAdEnabled) return "";
        
        if (cc.sys.os === cc.sys.OS.IOS) {           
            return ENV.SDK.IOS.PLACEMENT_IDS[type.toString()] || ENV.SDK.DEFAULT.BANNER;
        } else if (cc.sys.os === cc.sys.OS.ANDROID) {
            return ENV.SDK.ANDROID.PLACEMENT_IDS[type.toString()] || ENV.SDK.DEFAULT.BANNER;
        } 
        return ENV.SDK.DEFAULT.BANNER;
    }


    // 初始化激励广告
    initRewardedVideoTSSDK(){
        if (!this.isAdEnabled) return;
        
        ATRewardedVideoSDK.setAdListener(this);
        this.preloadRewardedVideoAd();
        console.log("initRewardedVideoTSSDK");
    }

    // 预加载激励视频广告
    private preloadRewardedVideoAd() {
        // 如果今日广告次数已达上限，则不预加载激励视频广告
        if (UserModel.getInstance().getTodayAdCount() >= ENV.MAX_AD_COUNT) return;

        if (!this.isAdEnabled || !ENV.REWARD_VIDEO_OPEN) return;
        
        const placementId = this.getPlacementId(PlacementType.REWARD_VIDEO);
        if (this.rewardedVideoCache.size < this.CACHE_SIZE) {
            let setting = {};
            setting[ATRewardedVideoSDK.userIdKey] = this.USER_ID;
            const randon = Math.random();
            // 游戏场景
            const game_scene = randon > 0.5 ? 'game_success' : 'game_fail';
            // 游戏奖励 双倍奖励，  获取道具
            const game_reward = randon > 0.5 ? 'double_reward' : 'get_item';
            const userData = new AdCustomRuleBuilder()
                .setUserId(this.USER_ID)
                .setAdScene(game_scene)
                .setRewardType(game_reward)
                .build();

            setting[ATRewardedVideoSDK.userDataKey] = userData;
            console.log("预加载激励视频广告", placementId, setting);
            ATRewardedVideoSDK.loadRewardedVideo(placementId, setting);
            this.rewardedVideoCache.set(placementId, false);
        }
    }

    // 显示RewardedVideo广告
    showRewardedVideoAd(scenario: string = ""){

        // 判断如果没有登录，则不显示激励视频广告
        if (!UserModel.getInstance().getUserInfo()) {
            GlobalEvent.emit(EventTypes.MAX_AD_COUNT_REACHED, "请退出APP，重新登录");
            return;
        };

        console.log("showRewardedVideoAd", UserModel.getInstance().getTodayAdCount(), ENV.MAX_AD_COUNT);
        // 如果今日广告次数已达上限，则不显示激励视频广告
        if (UserModel.getInstance().getTodayAdCount() >= ENV.MAX_AD_COUNT) return;


        if (!this.isAdEnabled || !ENV.REWARD_VIDEO_OPEN) return;
        
        const placementId = this.getPlacementId(PlacementType.REWARD_VIDEO);
        if (ATRewardedVideoSDK.hasAdReady(placementId)) {
            ATRewardedVideoSDK.showAdInScenario(placementId, scenario);
            this.rewardedVideoCache.delete(placementId);
            // 显示后立即预加载下一条
            this.preloadRewardedVideoAd();
        } else {
            console.log("激励视频广告未准备好");
        }
    }


    // RewardedVideo广告播放结束回调
    onRewardedVideoAdPlayEnd(placementId, callbackInfo) {
        console.log("RewardedVideo广告播放结束回调", placementId, callbackInfo, "");
        try {
            setTimeout(() => {
                this.uploadoRewardedVideoAdRewarded(placementId, callbackInfo);
            }, 1000);
        } catch (error) {
            console.log("RewardedVideo广告播放结束回调", placementId, callbackInfo, "");
        }
    }

    // 初次完整观看
    onReward(placementId, callbackInfo) {
        console.log("onReward 初次完整观看", placementId, callbackInfo, "");
        this.uploadoRewardedVideoAdRewarded(placementId, callbackInfo);
    }


    // 上传激励信息
    uploadoRewardedVideoAdRewarded(placementId, callbackInfo) {
        let appid = ENV.SDK.ANDROID.APP_ID;
        if (cc.sys.os === cc.sys.OS.IOS) {           
            appid = ENV.SDK.IOS.APP_ID;
        } else if (cc.sys.os === cc.sys.OS.ANDROID) {
            appid = ENV.SDK.ANDROID.APP_ID;
        }
        
        // 检查 callbackInfo 的类型并正确处理
        let remarkData = callbackInfo;
        if (typeof callbackInfo === 'string') {
            // 如果已经是字符串，尝试解析它以确认是否已是JSON字符串
            try {
                JSON.parse(callbackInfo);
                // 如果能解析成功，说明已经是JSON字符串，直接使用
                remarkData = callbackInfo;
            } catch (e) {
                // 如果解析失败，说明是普通字符串，需要转换
                remarkData = JSON.stringify(callbackInfo);
            }
        } else if (typeof callbackInfo === 'object') {
            // 如果是对象，转换为JSON字符串
            remarkData = JSON.stringify(callbackInfo);
        }
        
        let parsedInfo = null;
        try {
            // 检查 callbackInfo 是否已经是对象
            if (typeof callbackInfo === 'string') {
                parsedInfo = JSON.parse(callbackInfo);
            } else if (typeof callbackInfo === 'object' && callbackInfo !== null) {
                parsedInfo = callbackInfo;
            } else {
                console.warn("callbackInfo 类型不正确", typeof callbackInfo, callbackInfo);
                return;
            }
        } catch (e) {
            console.warn("callbackInfo 解析失败", callbackInfo);
            return;
        }
    
        const uniqueAdId = parsedInfo?.id;
        if (!uniqueAdId) {
            console.warn("缺少广告唯一 ID，不记录");
            return;
        }
        

        console.log("remarkData", remarkData);
        const ad_data = {
            appid: appid,
            ad_id: uniqueAdId.toString(),
            remark: remarkData
        }

        // 上传广告记录
        UserApi.uploadAdRecord(ad_data).then(res => {
            console.log("上传广告记录成功", JSON.stringify(res));
            GlobalEvent.emit(EventTypes.REWARD_VIDEO_AD_PLAY_END);
            // 增加用户广告次数
            UserModel.getInstance().addAdCount();
        }).catch(err => {
            console.log("上传广告记录失败", JSON.stringify(err));
        });
    }


    // 初始化Banner广告
    initBannerTSSDK(){
        if (!this.isAdEnabled || !ENV.BANNER_OPEN) return;
        
        console.log("initBannerTSSDK");
        ATBannerSDK.setAdListener(this);
        this.loadBannerAd();
        this.showBannerAd();
    }


    // 加载Banner广告
    loadBannerAd(placementType: PlacementType = PlacementType.BANNER, userData: any = null){
        if (!this.isAdEnabled || !ENV.BANNER_OPEN) return;
        
        console.log("loadBannerAd", this.getPlacementId(placementType));
        let setting = {};
            setting[ATBannerSDK.kATBannerAdLoadingExtraBannerAdSizeStruct] = ATBannerSDK.createLoadAdSize(cc.view.getFrameSize().width, 150);
            setting[ATBannerSDK.kATBannerAdAdaptiveWidth] = cc.view.getFrameSize().width;
        setting[ATBannerSDK.kATBannerAdAdaptiveOrientation] = ATBannerSDK.kATBannerAdAdaptiveOrientationPortrait;

        if(userData){
            setting[this.USER_DATA] = userData;
        }else{
            // 广告tag 首页Banner广告
            const userData = new AdCustomRuleBuilder()
                .setUserId(this.USER_ID)
                .setAdScene('home')
                .build();
            setting[this.USER_DATA] = userData;
        }
        ATBannerSDK.loadBanner(this.getPlacementId(PlacementType.BANNER), setting);
    }

    // 显示首页Banner广告
    showBannerAd(placementType: PlacementType = PlacementType.BANNER){
        if (!this.isAdEnabled || !ENV.BANNER_OPEN) return;
        
        console.log("showBannerAd", this.getPlacementId(placementType));
        ATBannerSDK.showAdInPosition(this.getPlacementId(placementType), ATBannerSDK.kATBannerAdShowingPositionTop);
    }

    // 重新显示Banner广告
    reShowBannerAd(placementType: PlacementType = PlacementType.BANNER) {
        if (!this.isAdEnabled || !ENV.BANNER_OPEN) return;
        
        printLog("reShowAd", this.getPlacementId(placementType), "", "")
        ATBannerSDK.reShowAd(this.getPlacementId(placementType));
    }

    // 隐藏Banner广告
    hideBannerAd(placementType: PlacementType = PlacementType.BANNER) {
        ATBannerSDK.hideAd(this.getPlacementId(placementType));
    }


    // 预加载个人中心Banner广告
    preloadPersonalCenterBannerAd(){
        if (!this.isAdEnabled || !ENV.BANNER_OPEN) return;
        this.loadBannerAd(PlacementType.PERSONAL_CENTER_BANNER);
    }


    // 显示个人中心Banner广告
    showPersonalCenterBannerAd(){
        if (!this.isAdEnabled || !ENV.BANNER_OPEN) return;
        if (this.personalTopBannerIsLoading) {
            this.reShowPersonalCenterBannerAd();
            return;
        };
        // 广告tag 个人中心Banner广告
        const userData = new AdCustomRuleBuilder()
            .setUserId(this.USER_ID)
            .setAdScene('personal_center')
            .build();

        this.loadBannerAd(PlacementType.PERSONAL_CENTER_BANNER, userData);
        this.showBannerAd(PlacementType.PERSONAL_CENTER_BANNER);
        this.personalTopBannerIsLoading = true;
    }

    // 重新显示个人中心Banner广告
    reShowPersonalCenterBannerAd() {
        if (!this.isAdEnabled || !ENV.BANNER_OPEN) return;
        this.reShowBannerAd(PlacementType.PERSONAL_CENTER_BANNER);
    }

    // 隐藏个人中心Banner广告
    hidePersonalCenterBannerAd() {
        this.hideBannerAd(PlacementType.PERSONAL_CENTER_BANNER);
    }

    // 原生广告
    initNativeAd(node: Node = null, placementType: PlacementType = PlacementType.NATIVE, setting: any = null){
        if (!this.isAdEnabled || !ENV.NATIVE_OPEN) return;
        console.log("anythink_network native_ad")
        ATNativeTSSDK.setAdListener(this);
        this.preloadNativeAd(placementType, setting);
        this.showNativeAd(node, placementType);
    }
    

    // 预加载原生广告
    private preloadNativeAd(placementType: PlacementType = PlacementType.NATIVE, userData: any = null) {
        if (!this.isAdEnabled || !ENV.NATIVE_OPEN) return;

        // 判断如果已经预加载过，则不预加载
        const placementId = this.getPlacementId(placementType);
        if (this.nativeAdCache.size < this.CACHE_SIZE) {
            // 获取屏幕尺寸
            const frameSize = cc.view.getFrameSize();
            const screenWidth = frameSize.width;
            
            // 计算广告尺寸 - 使用更合理的宽高比
            const adWidth = screenWidth * 1; // 广告宽度为屏幕宽度的90%
            const adHeight = adWidth * 0.6;   // 使用3:5的宽高比


            if(!userData){
                userData = new AdCustomRuleBuilder()
                    .setUserId(this.USER_ID)
                    .setAdScene('home')
                    .build();
            }
            let setting = {};
            setting[this.USER_DATA] = userData;

            setting['width'] = adWidth;
            setting['height'] = adHeight;
            
            console.log("预加载原生广告", placementId, setting);
            ATNativeTSSDK.loadNative(placementId, setting);
           
            // ATNativeTSSDK.loadNative(placementId, ATNativeTSSDK.createLoadAdSize(
            //     adWidth,
            //     adHeight
            // ));
            this.nativeAdCache.set(placementId, false);
        }
    }

    /**
     * 显示原生广告
     * @param adBannerNode 广告容器节点，用于确定广告的大小和位置
     */
    showNativeAd(adBannerNode: Node = null, placementType: PlacementType = PlacementType.NATIVE) {
        if (!this.isAdEnabled || !ENV.NATIVE_OPEN) {
            console.log("原生广告功能未启用");
            return;
        }
        
        const placementId = this.getPlacementId(placementType);
        if (!ATNativeTSSDK.hasAdReady(placementId)) {
            console.log("原生广告未准备好，开始预加载");
            this.preloadNativeAd(placementType);
            setTimeout(() => {
                this.showNativeAd(adBannerNode, placementType);
            }, 1000);
            return;
        }

        console.log("准备显示原生广告", placementId);

        // 如果没有提供节点，使用默认尺寸
        if (!adBannerNode) {
            let frameSize = view.getFrameSize();
            let frameWidth = frameSize.width;
            let frameHeight = frameSize.height;
            let padding = frameWidth / 35;
            
            // 设置宽度占满屏幕
            let parentWidth = frameWidth;
            // 保持合适的高宽比
            let parentHeight = frameWidth * (180 / 720);
            let appIconSize = frameWidth/7;
            
            // 计算y坐标，使广告显示在底部
            // 注意：屏幕坐标系原点在左上角，y轴向下为正
            let posY = frameHeight - parentHeight;
            
            this.showNativeAdWithSize(0, posY, parentWidth, parentHeight, appIconSize, padding, placementType);
            return;
        }

        // 获取节点的世界坐标和尺寸
        const uiTransform = adBannerNode.getComponent(UITransform);
        if (!uiTransform) {
            console.error("原生广告节点缺少UITransform组件");
            return;
        }
        
        const width = uiTransform.width;
        const height = uiTransform.height;
        
        // 获取节点在世界坐标系中的位置
        const worldPos = new Vec3();
        adBannerNode.getWorldPosition(worldPos);
        
        // 转换为屏幕坐标
        let screenPos;
        try {
            const camera = director.getScene().getComponentInChildren(Camera);
            if (!camera) {
                console.error("场景中没有找到Camera组件");
                return;
            }
            screenPos = camera.worldToScreen(worldPos);
        } catch (e) {
            console.error("转换世界坐标到屏幕坐标失败:", e);
            // 使用默认位置
            screenPos = {x: 0, y: 0};
        }
        
        console.log("原生广告节点信息:", {
            worldPos: worldPos,
            screenPos: screenPos,
            width: width,
            height: height
        });
        
        // 计算广告尺寸
        const frameSize = view.getFrameSize();
        const screenWidth = frameSize.width;
        const screenHeight = frameSize.height;
        
        // 适配不同分辨率设备
        const scale = screenWidth / 720; // 假设设计分辨率为720
        const adWidth = width * scale;
        const adHeight = height * scale;
        const appIconSize = adWidth / 7;
        const padding = adWidth / 35;

        // 计算广告位置（考虑节点中心点）
        const adX = Math.round(screenPos.x - adWidth / 2);
        const adY = Math.round(screenHeight - screenPos.y - adHeight / 2);

        console.log("即将显示原生广告:", {
            adX: adX,
            adY: adY,
            adWidth: adWidth,
            adHeight: adHeight
        });

        this.showNativeAdWithSize(adX, adY, adWidth, adHeight, appIconSize, padding, placementType);
    }

    /**
     * 根据指定尺寸显示原生广告
     * @private
     */
    private showNativeAdWithSize(
        parentX: number, 
        parentY: number, 
        parentWidth: number, 
        parentHeight: number, 
        appIconSize: number, 
        padding: number,
        placementType: PlacementType = PlacementType.NATIVE
    ) {
        if (!this.isAdEnabled || !ENV.NATIVE_OPEN) return;
        
        const placementId = this.getPlacementId(placementType);
        const nativeAdViewProperty = new AdViewProperty();
        
        // 设置父容器
        nativeAdViewProperty.parent = nativeAdViewProperty.createItemViewProperty(
            parentX, parentY, parentWidth, parentHeight, "#ffffff", "", 0
        );

        // 设置各个广告元素的位置和大小
        nativeAdViewProperty.appIcon = nativeAdViewProperty.createItemViewProperty(
            0, parentHeight - appIconSize, appIconSize, appIconSize, "", "", 0
        );
        
        nativeAdViewProperty.cta = nativeAdViewProperty.createItemViewProperty(
            parentWidth - appIconSize * 2, parentHeight - appIconSize,
            appIconSize * 2, appIconSize, "#2095F1", "#ffffff", appIconSize/3
        );

        nativeAdViewProperty.mainImage = nativeAdViewProperty.createItemViewProperty(
            padding, padding,
            parentWidth - 2 * padding, parentHeight - appIconSize - 2 * padding,
            "#ffffff", "#ffffff", 14
        );

        nativeAdViewProperty.title = nativeAdViewProperty.createItemViewProperty(
            appIconSize + padding, parentHeight - appIconSize,
            parentWidth - 3 * appIconSize - 2 * padding, appIconSize/2,
            "", "#000000", appIconSize/3
        );

        nativeAdViewProperty.desc = nativeAdViewProperty.createItemViewProperty(
            appIconSize + padding, parentHeight - appIconSize/2,
            parentWidth - 3 * appIconSize - 2 * padding, appIconSize/2,
            "#ffffff", "#000000", appIconSize/4
        );

        nativeAdViewProperty.dislike = nativeAdViewProperty.createItemViewProperty(
            parentWidth - appIconSize/2, 0,
            appIconSize/2, appIconSize/2,
            "#00ffffff", "#ffffff", 14
        );

        nativeAdViewProperty.elements = nativeAdViewProperty.createItemViewProperty(
            0, parentHeight - appIconSize/2,
            parentWidth, appIconSize/2,
            "#7f000000", "#ffffff", 14
        );

        ATNativeTSSDK.showAd(placementId, nativeAdViewProperty);
        this.nativeAdCache.delete(placementId);
    }

    // 移除原生广告
    removeNativeAd(placementType: PlacementType = PlacementType.NATIVE){
        ATNativeTSSDK.removeAd(this.getPlacementId(placementType));
        printLog("removeAd", this.getPlacementId(PlacementType.NATIVE), "", "")
    }

    // 预加载插播广告
    preloadInterstitialAd(userData: any = null) {
        if (!this.isAdEnabled || !ENV.INTERSTITIAL_OPEN) return;
        
        const placementId = this.getPlacementId(PlacementType.INTERSTITIAL);
        if (this.interstitialAdCache.size < this.CACHE_SIZE) {
            let setting = {};
            setting[this.USER_ID] = this.USER_ID;

            if(!userData ){
                // 广告tag 插播广告 
                // 获取光卡
                try{
                    const game_level_key = "game_level" + this._appid;
                    const game_level = localStorage.getItem(game_level_key) ;
                    if(game_level){
                        userData = new AdCustomRuleBuilder()
                            .setAdScene('game_level')
                            .setLevel(Number(game_level))
                            .build();
                    }
                }catch(e){
                    console.log("获取光卡失败", e);
                }
            }
            setting[this.USER_DATA] = userData;
            ATInterstitialSDK.loadInterstitial(placementId, setting);
            this.interstitialAdCache.set(placementId, false);
        }
    }

    // 显示插播广告
    showInterstitialAd(){
        if (!this.isAdEnabled || !ENV.INTERSTITIAL_OPEN) return;
        
        const placementId = this.getPlacementId(PlacementType.INTERSTITIAL);
        if (ATInterstitialSDK.hasAdReady(placementId)) {
            ATInterstitialSDK.showAd(placementId);
            this.interstitialAdCache.delete(placementId);
            // 显示后立即预加载下一条
            this.preloadInterstitialAd();
        } else {
            console.log("插播广告未准备好");
        }
    }


    // 添加获取广告状态的方法
    isAdOpen(): boolean {
        return this.isAdEnabled;
    }
}


let printLog = function(methodName, placementId, callbackInfo, errorInfo) {
  ATJSSDK.printLogWithParams("AnyThinkRewardedVideoDemo", methodName, placementId, callbackInfo, errorInfo)
}
